package com.daxue.configtest.base;

import com.daxue.configtest.exception.impl.BadArgumentException;
import com.daxue.configtest.exception.impl.ConflictException;
import com.daxue.configtest.exception.impl.NotFoundException;
import org.jooq.UpdatableRecord;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.Optional;

/**
 * @author daxue0929
 * @date 2023/3/23
 */

public abstract class BaseDAO<R extends UpdatableRecord<R>, E extends BaseEntity>
    extends BaseRepository<R, E> implements DAO<R, E>{

    @Override
    public E create(final E entity) throws ConflictException, BadArgumentException {
        entity.setId(null);
        return create0(entity);
    }

    @Override
    public E create(final String id, final E entity) throws BadArgumentException, ConflictException {
        entity.setId(id);
        return create0(entity);
    }

    @Override
    public Optional<E> find(final String id) throws ConflictException {
        return read0(Sort.unsorted(), QueryConditions.where(primaryKey().eq(id)));
    }

    @Override
    public E read(final String id) throws NotFoundException, ConflictException {
        return read0(Sort.unsorted(), QueryConditions.where(primaryKey().eq(id)))
            .orElseThrow(this::notFoundException);
    }

    @Override
    public Optional<E> findOne(final Sort sort, final QueryConditions condition) throws ConflictException {
        return read0(sort, condition);
    }

    @Override
    public Optional<E> findOne(final QueryConditions conditions) throws ConflictException {
        return read0(Sort.unsorted(), conditions);
    }

    @Override
    public E readOne(final Sort sort, final QueryConditions condition) throws NotFoundException, ConflictException {
        return read0(sort, condition).orElseThrow(this::notFoundException);
    }

    @Override
    public E readOne(final QueryConditions conditions) throws NotFoundException, ConflictException {
        return read0(Sort.unsorted(), conditions).orElseThrow(this::notFoundException);
    }

    @Override
    public Page<E> readAll(final Pageable pageable, final QueryConditions condition) throws ConflictException {
        return readAll0(pageable, condition);
    }

    @Override
    public E update(final String id, final E entity) throws NotFoundException, ConflictException, BadArgumentException {
        return update0(entity, QueryConditions.where(primaryKey().eq(id)));
    }

    @Override
    public E delete(final String id) throws NotFoundException, ConflictException {
        return delete0(QueryConditions.where((primaryKey().eq(id))));
    }

    @Override
    public Page<E> deleteAll(final QueryConditions conditions) throws ConflictException {
        return deleteAll0(conditions);
    }
}
